package com.banfan.almond.web.security;


import com.banfan.almond.utils.RedisUtil;
import com.banfan.almond.utils.ResultUtil;
import com.banfan.almond.web.global.JwtConf;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.TimeUnit;

@Component
@Slf4j
public class LoginSuccessHandler implements AuthenticationSuccessHandler {


    @Autowired
    private RedisUtil redisUtil;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest httpServletRequest,
                                        HttpServletResponse httpServletResponse,
                                        Authentication authentication) throws IOException, ServletException {

//        httpServletResponse.setContentType("application/json;charset=UTF-8");
//        ServletOutputStream outputStream = httpServletResponse.getOutputStream();
//
//        UsernamePasswordAuthenticationToken authentication1 = (UsernamePasswordAuthenticationToken) authentication;
//        SecurityUser principal = (SecurityUser) authentication1.getPrincipal();
//        String username = principal.getUsername();
//        String password = principal.getPassword();
//
//        //jwt
//        String jwt = JwtUtil.createJWT(username, JwtConf.TOW_MINUTE);
//
//        //返回响应
//        String result = ResultUtil.successWithData(jwt);
//        outputStream.write(result.getBytes(StandardCharsets.UTF_8));
//        outputStream.flush();
//        outputStream.close();
//
//        //存入token:userName
//        redisUtil.setEx(jwt, username, 7, TimeUnit.DAYS);
//
//
//        String  x = "1342";

    }
}
